package cn.itcast.web.fliter;
/*
 * @author skycat
 * @time 2021/12/31
 */

import cn.itcast.pojo.AdminUser;


import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //先判断是不是可以放行的资源，登录界面和登录的servlet，验证码的servlet，相关资源
        String uri = httpServletRequest.getRequestURI();
        if (uri.contains("/login.jsp") || uri.contains("/loginServlet") ||
                uri.contains("/checkCodeServlet") || uri.contains("/resource")) {
            chain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            AdminUser user = (AdminUser) httpServletRequest.getSession().getAttribute("adminUser");
            if(user!=null){
                chain.doFilter(httpServletRequest, httpServletResponse);
            }else{
                httpServletRequest.setAttribute("login_msg","您还未登录，请先登录！");
                httpServletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest,httpServletResponse);
            }
        }
    }

    public void init(FilterConfig config)  {
    }

    public void destroy() {
    }
}
